import { createRouter, createWebHistory } from 'vue-router'
import type { RouteLocationNormalized } from 'vue-router'
import Layout from '../components/layout/Layout.vue'
import { useUserStore } from '../stores/user'
import { ElMessage } from 'element-plus'

// 预加载函数
const loadView = (view: string) => {
    return () => import(/* webpackChunkName: "[request]" */ `../views/${view}.vue`)
}

// 预加载特定视图
const preloadViews = () => {
    // 预加载核心页面，减少切换延迟
    const commonViews = [
        'home/Home',
        'category/Category',
        'search/Search',
        'user/UserCenter'
    ]

    for (const view of commonViews) {
        loadView(view)()
    }
}

// 基础路由 - 静态路由
const routes = [
    {
        path: '/',
        component: Layout,
        children: [
            {
                path: '',
                name: 'Home',
                component: () => import(/* webpackPrefetch: true */ '../views/home/Home.vue'),
                meta: {
                    title: '首页',
                    keepAlive: true
                }
            },
            {
                path: 'modern',
                name: 'ModernHome',
                component: () => import(/* webpackPrefetch: true */ '../views/home/ModernHome.vue'),
                meta: {
                    title: '现代首页',
                    keepAlive: true
                }
            },
            {
                path: '/map',
                name: 'Map',
                component: () => import('../views/map/Map.vue'),
                meta: {
                    title: '地图',
                    keepAlive: true
                }
            },
            {
                path: 'login',
                name: 'Login',
                component: () => import('../views/Login.vue'),
                meta: {
                    title: '登录',
                    keepAlive: false
                }
            },
            {
                path: 'register',
                name: 'Register',
                component: () => import('../views/Register.vue'),
                meta: {
                    title: '注册',
                    keepAlive: false
                }
            },
            {
                path: 'product/:id',
                name: 'ProductDetail',
                component: () => import('../views/product/ProductDetail.vue'),
                meta: {
                    title: '商品详情',
                    keepAlive: false
                }
            },
            {
                path: 'category',
                name: 'Category',
                component: () => import('../views/category/Category.vue'),
                meta: {
                    title: '商品',
                    keepAlive: true
                }
            },
            {
                path: 'category/:id',
                name: 'CategoryDetail',
                component: () => import('../views/category/CategoryDetail.vue'),
                meta: {
                    title: '分类详情',
                    keepAlive: false
                }
            },
            {
                path: 'search',
                name: 'Search',
                component: () => import('../views/search/Search.vue'),
                meta: {
                    title: '搜索',
                    keepAlive: false
                }
            },
            {
                path: 'school/:id',
                name: 'SchoolDetail',
                component: () => import('../views/school/SchoolDetail.vue'),
                meta: {
                    title: '学校详情',
                    keepAlive: false
                }
            },
            {
                path: 'schools',
                name: 'Schools',
                component: () => import('../views/school/Schools.vue'),
                meta: {
                    title: '学校列表',
                    keepAlive: true
                }
            },
            {
                path: 'user/products',
                name: 'MyProducts',
                component: () => import('../views/user/MyProducts.vue'),
                meta: {
                    title: '我的商品',
                    keepAlive: true
                }
            },
            {
                path: 'user/profile',
                alias: '/user/profile',
                name: 'Profile',
                component: () => import('../views/user/Profile.vue'),
                meta: {
                    title: '个人资料',
                    keepAlive: false
                }
            },
            {
                path: 'user/center',
                alias: '/user/center',
                name: 'UserCenter',
                component: () => import('../views/user/UserCenter.vue'),
                meta: {
                    title: '个人中心',
                    keepAlive: true
                }
            },
            {
                path: 'user/orders',
                alias: '/user/orders',
                name: 'Orders',
                component: () => import('../views/user/Orders.vue'),
                meta: {
                    title: '我的订单',
                    keepAlive: true
                }
            },
            {
                path: 'order/:id',
                name: 'OrderDetail',
                component: () => import('../views/order/OrderDetail.vue'),
                meta: {
                    title: '订单详情',
                    keepAlive: false,
                    requiresAuth: true
                }
            },
            {
                path: 'user/favorites',
                alias: '/user/favorites',
                name: 'Favorites',
                component: () => import('../views/user/Favorites.vue'),
                meta: {
                    title: '我的收藏',
                    keepAlive: true
                }
            },
            {
                path: 'user/wallet',
                alias: '/user/wallet',
                name: 'Wallet',
                component: () => import('../views/user/UserCenter.vue'),
                meta: {
                    title: '我的钱包',
                    keepAlive: true
                }
            },
            {
                path: 'user/settings',
                alias: '/user/settings',
                name: 'Settings',
                component: () => import('../views/user/UserCenter.vue'),
                meta: {
                    title: '设置',
                    keepAlive: true
                }
            },
            {
                path: 'cart',
                name: 'Cart',
                component: () => import('../views/cart/Cart.vue'),
                meta: {
                    title: '购物车',
                    keepAlive: true
                }
            },
            {
                path: 'chat',
                alias: '/chat',
                name: 'Chat',
                component: () => import('../views/chat/Chat.vue'),
                meta: {
                    title: '聊天',
                    keepAlive: true
                }
            },
            {
                path: 'requests',
                name: 'Requests',
                component: () => import('../views/requests/Requests.vue'),
                meta: {
                    title: '用户求购',
                    keepAlive: true
                }
            }
        ]
    },
    // 404捕获路由 - 必须放在最后
    {
        path: '/:pathMatch(.*)*',
        name: 'NotFound',
        component: () => import('../views/NotFound.vue'),
        meta: {
            title: '404 - 页面未找到'
        }
    }
];

// 创建路由实例
const router = createRouter({
    history: createWebHistory(import.meta.env.BASE_URL),
    routes,
    // 增加滚动行为控制
    scrollBehavior(to, from, savedPosition) {
        if (savedPosition) {
            return savedPosition
        } else {
            return { top: 0 }
        }
    }
});

// 触发预加载
preloadViews()

// 保存上一页路由，用于判断是否需要重新加载数据
let previousRoute: any = null

// 路由守卫
router.beforeEach((to, from, next) => {
    console.log('Navigation to:', to.path);
    console.log('Route matched:', to.matched.map(record => record.path));

    const userStore = useUserStore();

    // 记录上一次路由，用于判断是否是返回操作
    previousRoute = from;

    // 权限控制
    const publicPages = ['/login', '/register', '/', '/modern', '/schools', '/product', '/map', '/category', '/requests'];
    const authRequired = !publicPages.some(path => to.path.startsWith(path)) || to.meta.requiresAuth;

    if (authRequired && !userStore.isLoggedIn) {
        next({
            path: '/login',
            query: { redirect: to.fullPath }
        });
    } else {
        next();
    }
});

export default router; 